import React, { useState } from 'react';

const ProductView = () => {
  const [user, setUser] = useState({
    username: '', password: '', infos: '', likes: 'lime', sex: '女',
    girls: ['王祖贤', '刘京生', '张曼玉', '赵雅芝', '刘德华']
  });
  const [friends, setFriends] = useState(['三太子', '白龙马', '大师兄', '王祖贤', '刘京生', '张曼玉', '赵雅芝', '刘德华'])

  const submitHandler = (e) => {
    console.log(user)
  }
  const editUserName = (e) => {
    setUser({
      ...user, username: e.target.value
    })
  }
  const editPassword = (e) => {
    setUser({
      ...user, password: e.target.value
    })
  }

  const editInfos = (e) => {
    setUser({
      ...user, infos: e.target.value
    })
  }

  const editLikes = (e) => {
    console.log(e.target.value)
    // 多选时，值是数组
    // setUser({
    //   ...user, likes: Array.from(new Set([...user.likes, e.target.value]))
    // })

    // 单选
    setUser({
      ...user, likes: e.target.value
    })
  }

  const getSexValue = (e) => {
    setUser({
      ...user, sex: e.target.value,
    })
  }

  const editGirls = (e) => {
    let changeGirlName = e.target.value;
    let tempArr = user.girls;
    let resultState = tempArr.some(el => el === changeGirlName)
    // console.log(resultState)
    // console.log(tempArr)

    if (resultState === true) {
      // 取消选中，从数组里面删除
      tempArr = tempArr.filter(el => el !== changeGirlName)
      // console.log(tempArr)
    } else {
      // 选中，添加到数组里面
      tempArr.push(changeGirlName)
    }
    setUser({
      ...user, girls: tempArr,
    })
  }
  return (
    <form>
      <div>
        UserName:<input type='text' value={user.username} onChange={editUserName} />
      </div>
      <div>
        PassWord:<input type='password' value={user.password} onChange={editPassword} />
      </div>
      <div>
        infos: <textarea value={user.infos} onChange={editInfos} name="infos" id="" cols="30" rows="10">元素内容就是textarea对象的值</textarea>
      </div>
      <div>
        爱好： <select value={user.likes} onChange={editLikes}>
          <option value="grapefruit">葡萄柚</option>
          <option value="lime">酸橙</option>
          <option value="coconut">椰子</option>
          <option value="mango">芒果</option>
        </select>
      </div>
      <div>
        sex: <input type="radio" name="sex" value="男" checked={user.sex === '男'} onChange={getSexValue} />男
        <input type="radio" name="sex" value="女" checked={user.sex === '女'} onChange={getSexValue} />女
      </div>
      <div>
        you friends:
        {
          friends.map((el, index) => <label key={index}><input onChange={editGirls} checked={user.girls.some(item => el === item)} type="checkbox" value={el} />{el}</label>)

        }

      </div>
      <div>
        <button type="button" onClick={submitHandler}>submit</button>
      </div>
    </form>
  );
}

export default ProductView;
